package com.lee.dianjiqi;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.lee.dianjiqi.timing.ThreadPoolUtil;

import java.lang.ref.WeakReference;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class FloatingTimeService extends Service {

    private static final int TIME_WHAT = 0x002;

    private static final String TAG = "FloatingTimeService";
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    private TextView textTime;

    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        initMainView();

    }

    private void initMainView() {

        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.x = 50;
        layoutParams.y = 50;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "==========onStartCommand===========");
        isStart = false;

        showFloatingWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    @SuppressLint("NewApi")
    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this)) {
            addMainView();
        }
    }

    private ScheduledFuture scheduledFuture;

    private void addMainView() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.layout_time, null);
        textTime = inflate.findViewById(R.id.textTime);

        windowManager.addView(inflate, layoutParams);

        scheduledFuture = ThreadPoolUtil.getInstance().scheduleAtFixedRate(runnable, 0, 100L, TimeUnit.MILLISECONDS);
        inflate.setOnTouchListener(new FloatingOnTouchListener());

    }

    private void stopExecute() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopExecute();
    }

    public void updateTime() {
        textTime.setText(DateHelper.getCurDateStr(DateHelper.FORMAT_COUNT));
    }

    boolean isStart = false;

    public static class MyHandler extends Handler {
        private WeakReference<FloatingTimeService> reference;

        public MyHandler(FloatingTimeService service) {
            reference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {

            FloatingTimeService service = reference.get();

            if (service == null)
                return;

            service.updateTime();

        }
    }


    MyHandler handler = new MyHandler(this);

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.sendEmptyMessage(TIME_WHAT);
        }
    };


    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }
}